$(document).ready(function(){
    socia_init();
});

function socia_init() {
    $('#leaving, #joining').on('click', socia_action);
}

function socia_action() {
    if(typeof ago_url === "undefined" || typeof kom_type === "undefined") {
        console.log('AJAX Context not found!');
        return;
    }

    let target = $(this);
    let data = socia_data(kom_type);

    if(!data) {
        console.log('No data for AJAX');
        return;
    }

    target.unbind('click', socia_action);
    toggleBlockForm(target, 24);

    $.ajax({
        url: ago_url,
        type: 'POST',
        async: true,
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false
    })
        .done(function (result) {
            if(result.status === 'ok') {
                setTimeout(function(){
                    $('#tuta').text(result.tuta);
                    $('.progress-bar .progress').css('width', result.procentoj + '%');
                    $('#joining, #leaving').parent().toggleClass('hidden-element');
                    toggleBlockForm(target);
                    target.on('click', socia_action);
                }, 1000);
            } else {
                console.log("Bad server response: " + result.err);
                toggleBlockForm(target);
            }
        })
        .fail(function (jqXHR, textStatus) {
            toggleBlockForm(target);
            console.log("Request failed: " + textStatus);
        });
}

function socia_data(type) {
    let uuid = $('*[data-' + type + '_uuid]').attr('data-' + type + '_uuid');

    if(uuid !== undefined) {
        out = new FormData();
        out.append(type, uuid);
        out.append('csrfmiddlewaretoken', getCookie('csrftoken'));

        return out;
    }

    return false;
}